<template>
  <a-menu v-model:openKeys="openKeys" v-model:selectedKeys="selectedKeys" class="app-menu" mode="inline" theme="dark" @openChange="handleOpenChange" @click="handleClickMenu">
    <template v-for="(nav) in sideBar" :key="nav.path">
      <template v-if="nav.children.length === 1">
        <a-menu-item :key="nav.path" :title="nav.children[0].meta.title">
          <Icon :type="nav.children[0].meta.icon" />
          <span>{{ nav.children[0].meta.title }}</span>
        </a-menu-item>
      </template>
      <template v-else>
        <a-menu-item v-if="!nav.children" :key="nav.path" :path="nav.path" :title="nav.meta.title">
          <span>{{ nav.meta.title }}</span>
        </a-menu-item>
        <sub-menu v-else :key="nav.path" :nav="nav" />
      </template>
    </template>
  </a-menu>
</template>

<script lang="ts">
import { defineComponent, computed, } from 'vue'
import { useStore } from 'vuex'
import router from '/@/router/index'
import SubMenu from './SubMenu/index.vue'

export default defineComponent({
  components: {
    SubMenu,
  },
  setup() {
    const sideBar = []
    const store = useStore()
    const routes = router.options.routes

    const selectedKeys = computed({
      get: () => [store.state.tabsView.activeKey],
      set: v => v
    })
    const openKeys = computed({
      get: () => store.state.tabsView.openKeys,
      set: v => v
    })

    routes.map(r => {
      if (r.children && !r.meta.hidden) {
        r.children = r.children.filter(m => !m.meta.hidden)
        sideBar.push(r)
      } else if (!r.meta.hidden) {
        sideBar.push(r)
      }
    })

    return {
      sideBar,
      selectedKeys,
      openKeys,
    }
  },
  methods: {
    handleClickMenu (val) {
      this.$router.push({ path: val.key })
      this.$store.commit('tabsView/SET_ACTICVE_KEY', val.key)
      this.$store.commit('tabsView/ADD_TAB', {
        title: val.item.title,
        path: val.key
      })
    },
    handleOpenChange (openKeys) {
      this.$store.commit('tabsView/SET_OPEN_KEYS', openKeys)
    }
  }
})
</script>

<style>
</style>
